package com.atguigu.spzx.manager.service.impl;

import com.atguigu.spzx.common.handler.exception.SpzxException;
import com.atguigu.spzx.manager.properties.MinioUtil;
import com.atguigu.spzx.manager.properties.SpzxMinioProperties;
import com.atguigu.spzx.manager.service.FileService;
import com.atguigu.spzx.model.common.ResultCodeEnum;
import io.minio.BucketExistsArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import io.minio.errors.*;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * title:
 * author: zgl
 * date: 2023/12/29
 * description：
 */
@Service
public class FileServiceImpl implements FileService {
    @Override
    public String upload(String module, MultipartFile file) {
        try {
            //获取文件名
            String uploadFile = file.getOriginalFilename();
            //获取流
            InputStream inputStream = file.getInputStream();
            //拼接上传格式// module/2023-12/29/123123124124_1231ab123.png
            String filename = module + new DateTime().toString("/yyyy-MM/dd/") +
                    UUID.randomUUID().toString().substring(0, 6) + uploadFile.substring(uploadFile.lastIndexOf("."));
            //获取Minio对象
            MinioUtil.getMinioClient().putObject(PutObjectArgs.builder().stream(inputStream, inputStream.available(), -1)
                    .bucket(SpzxMinioProperties.BUCKET_NAME)
                    .object(filename).build());
            //返回的路径
            //http://192.168.144.100:9000/spzx-bucket/idcard/2023-12/29/1703813215915_d65988.png
            String path = SpzxMinioProperties.ENDPOINT + "/" + SpzxMinioProperties.BUCKET_NAME +
                    "/" + filename;
            return path;
        } catch (Exception e) {
            throw new SpzxException(ResultCodeEnum.FILE_UPLOAD_ERROR,e);
        }
    }


    @Override
    public void delete(String path) {
        try {
            String delPath = path.substring((SpzxMinioProperties.ENDPOINT + "/"
                    + SpzxMinioProperties.BUCKET_NAME + "/").length());
            MinioUtil.getMinioClient().removeObject(RemoveObjectArgs.builder().object(delPath)
                    .bucket(SpzxMinioProperties.BUCKET_NAME)
                    .build());
        } catch (Exception e) {
            throw new SpzxException(ResultCodeEnum.FILE_DELETE_ERROR,e);
        }

    }
}
